<template>
  <div>
    <a-table
      v-model:selectedKeys="initData.data.selectedList"
      row-key="id"
      :loading="initData.data.loading"
      :data="initData.data.result.records || initData.data.result"
      :bordered="bordered ? false : { cell: true }"
      :pagination="false"
      :row-selection="checkbox ? initData.data.rowSelection : undefined"
      :scroll="{ x: '100%' }"
      @selection-change="selectTableChanges"
    >
      <!--:pagination="enablePagination ? initData.data.result : false"-->
      <!--@page-change="(number) => {initData.data.params.pageNumber = number;}"-->
      <template #columns>
        <!-- 循环表头 -->
        <a-table-column
          v-for="(item, index) in props.columns"
          :key="index"
          :title="item.title"
          :data-index="item.dataIndex"
          :tooltip="true"
          :width="item.width || 100"
          :fixed="item?.fixed"
          :ellipsis="!item.hasOwnProperty('ellipsis') ? true : item.ellipsis"
          :align="item.currency ? 'right' : 'left'"
        >
          <!-- 自定义模版 -->
          <template
            v-if="item.slot || item.currency || item.empty || item.render"
            #cell="{ record, column, rowIndex }"
          >
            <!-- 插槽 自定义-->
            <slot
              v-if="item.slot && item.slotTemplate"
              :name="item.slotTemplate"
              :record="record[item.dataIndex]"
              :column="column"
              :row-index="rowIndex"
              :data="record"
            ></slot>
            <!-- 标签展示 -->
            <a-tag
              v-if="item.slot && item.slotData?.tag"
              :color="findTagValue(item, record, 'color')"
              >{{ findTagValue(item, record, 'label') }}</a-tag
            >
            <!-- 商品展示 -->
            <div v-if="item.slot && item.slotData?.goods" class="flex">
              <a-image
                width="50"
                height="50"
                :src="record[item.slotData.goods.goodsImage]"
                show-loader
              >
                <template #loader>
                  <div class="loader-animate" />
                </template>
              </a-image>
              <div style="margin-left: 10px">
                <a-typography-text bold>
                  {{ record[item.slotData.goods.goodsName] }}
                </a-typography-text>
                <div class="flex">
                  <div v-if="record?.id">
                    <a-typography-text style="font-size: 12px" type="secondary">
                      ID:
                    </a-typography-text>
                    <a-typography-text
                      style="font-size: 12px"
                      type="secondary"
                      copyable
                    >
                      {{ record.id }}
                    </a-typography-text>
                  </div>
                </div>
                <!-- 商品其他信息 -->
                <div class="flex">
                  <div v-if="record?.goodsUnit">
                    <a-typography-text style="font-size: 12px" type="warning">
                      {{ record.goodsUnit }}
                    </a-typography-text>
                  </div>
                  <div v-if="record?.salesModel">
                    <a-typography-text
                      style="font-size: 12px"
                      type="success"
                      v-if="record?.salesModel == 'RETAIL'"
                    >
                      &nbsp;零售
                    </a-typography-text>
                    <a-typography-text
                      style="font-size: 12px"
                      type="success"
                      v-if="record?.salesModel == 'WHOLESALE'"
                    >
                      &nbsp;批发
                    </a-typography-text>
                  </div>
                  <div v-if="record?.goodsType">
                    <a-typography-text
                      style="font-size: 12px"
                      type="primary"
                      v-if="record?.goodsType == 'PHYSICAL_GOODS'"
                    >
                      &nbsp;实物商品
                    </a-typography-text>
                    <a-typography-text
                      style="font-size: 12px"
                      type="primary"
                      v-if="record?.goodsType == 'VIRTUAL_GOODS'"
                    >
                      &nbsp;虚拟商品
                    </a-typography-text>
                  </div>
                  <!-- <a-popover title="扫码查看商品">
                    <img class="qrcode" :src="qrcode" />
                    <template #content>
                      <vue-qrcode value="Hello, World!" :options="{ width: 200 }"></vue-qrcode>
                    </template>
                  </a-popover> -->
                  <a-typography-text
                    v-if="item.slotData?.isCopy"
                    class="copy-goods"
                    type="secondary"
                    @click="copyGoods(record.id)"
                  >
                    复制商品
                  </a-typography-text>
                </div>
              </div>
            </div>
            <!-- 货币展示 -->
            <a-typography-text v-if="item.currency">
              {{ unitPrice(record[item.dataIndex], '¥') }}
            </a-typography-text>
            <!-- 空值展示 -->
            <a-typography-text v-if="item.empty">
              {{ record[item.dataIndex] || item.empty }}</a-typography-text
            >
            <!-- 徽标展示 -->
            <div v-if="item.slot && item.slotData?.badge">
              <a-badge
                style="margin-right: 5px"
                :color="findTagValue(item, record, 'color', 'badge')"
              ></a-badge
              >{{ findTagValue(item, record, 'label', 'badge') }}
            </div>
          </template>
        </a-table-column>
        <!-- 方法 -->
        <a-table-column
          v-if="props?.methods?.methods"
          :width="props.methods?.width"
          align="center"
          :title="props.methods?.title"
          :fixed="props.methods?.fixed"
        >
          <template #cell="{ record, column, rowIndex }">
            <a-space>
              <div v-for="(btn, index) in props.methods.methods" :key="index">
                <!-- 插槽 自定义-->
                <slot
                  v-if="btn.slot && btn.slotTemplate"
                  :name="btn.slotTemplate"
                  :record="record"
                  :column="column"
                  :row-index="rowIndex"
                  :data="record"
                ></slot>
                <a-button
                  v-else
                  size="small"
                  class="btn"
                  :type="btn.type"
                  :status="btn.status"
                  @click="
                    handleClickBtn({
                      ...btn,
                      record: { ...record, ...column, ...rowIndex },
                    })
                  "
                  >{{ btn.title }}
                </a-button>
              </div>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <div v-if="enablePagination" class="paginationBox">
      <a-pagination
        :total="initData.data.result.total"
        :show-page-size="apiParams.pageSize ? false : true"
        :current="initData.data.params.pageNumber"
        :page-size="initData.data.params.pageSize"
        @change="
          (number) => {
            initData.data.params.pageNumber = number;
          }
        "
        @page-size-change="
          (number) => {
            initData.data.params.pageSize = number;
          }
        "
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import getAssetsImages from '@/utils/assetsImages';
  import { unitPrice } from '@/utils/filters';
  import VueQrcode from '@chenfengyuan/vue-qrcode';
  import { onMounted, reactive, ref, toRefs, watch } from 'vue';
  import { useRouter } from 'vue-router';

  const router = useRouter();
  const qrcode = getAssetsImages('qrcode.svg');

  interface InitProps {
    columns: any;
    methods: any;
    max?: string | number;
    api: any;
    dataList?: any;
    apiParams?: any;
    customApiParams?: any;
    enablePagination?: boolean;
    checkbox?: boolean;
    bordered?: boolean;
    radio?: boolean;
    defaultRowKey?: string;
    defaultSelectedKeys?: any;
  }

  interface InitDataRule {
    data: {
      result: {
        current: number | string;
        total: number;
        records: any[];
        [key: string]: any;
      };
      loading: boolean;
      rowSelection: {
        type: string;
        showCheckedAll: boolean;
        onlyCurrent: boolean;
        selectedRowKeys: Array<string | number>; // 已选择的行（受控模式）
        [key: string]: any;
      };
      params: {
        pageNumber?: number; // 当前页数
        pageSize: number; // 页面大小
        sort: string; // 默认排序字段
        order: string;
      };
      recordsList: any[];
      selectedRowList: any[];
      selected: any[];
      ids: any;
      selectedList: any[];
    };
  }

  const props = withDefaults(defineProps<InitProps>(), {
    columns: [],
    methods: {},
    // 最大显示内容 一般来说就是不分页的话才会使用到
    max: '',
    // 请求接口
    api: '',
    // 不请求接口 传数据
    dataList: '',
    // 附加请求参数
    apiParams: '',
    // 自定义请求参数
    customApiParams: '',
    // 是否展示分页
    enablePagination: true,
    checkbox: false,
    radio: false,
    // 是否展示边框
    bordered: false,
    // 表格行key的取值字段
    defaultRowKey: 'id',
    defaultSelectedKeys: [],
  });

  const initData: any = reactive<InitDataRule>({
    data: {
      result: {
        current: 1,
        total: 0,
        records: [],
      }, // 请求内容
      loading: false, // 加载动画
      rowSelection: {
        type: props.radio ? 'radio' : 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
        selectedRowKeys: [],
      },
      params: {
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        sort: 'createTime', // 默认排序字段
        order: 'desc', // 默认排序方式
      },
      recordsList: [], // 查询的数据总合
      selectedRowList: [],
      selected: [], // 已选择的商品
      ids: [],
      selectedList: [],
    },
  });
  const defaultRow = ref<any>([]);
  const emit = defineEmits([
    'selectTableChange',
    'parentComponentData',
    'selectionChanges',
  ]);
  // 已选择的数据行发生改变时触发
  const selectTableChanges = (keys: Array<string | number>) => {
    emit('selectionChanges', keys);
    initData.data.ids = keys;
    initData.data.rowSelection.selectedRowKeys = keys;
    // 将id进行循环赋值给父级
    const exportTableList: any = [];
    if (initData.data.selectedRowList.length) {
      keys.forEach((id) => {
        exportTableList.push(
          // initData.data.recordsList.find((item) => {return item.id == id;})
          // initData.data.selectedRowList.find((item) => {return item.skuId == id})
          initData.data.selectedRowList.find((item: any) => {
            return item.id == id;
          })
        );
      });
    }
    //  将选择的内容抛给子级
    emit('selectTableChange', exportTableList.length ? exportTableList : keys);
  };

  // find tag/badge
  const findTagValue = (
    item: any,
    record: any,
    key: string,
    search = 'tag'
  ) => {
    if (item.slotData[search] instanceof Array) {
      const temp = item.slotData[search].find((tag: any) => {
        return tag.value === record[item.dataIndex];
      });
      return temp ? temp[key] : temp;
    }
  };

  // 初始化内容
  async function init(val = {}) {
    initData.data.loading = true;
    const { apiParams } = toRefs(props);
    let submit;
    props.apiParams
      ? (submit = { ...val, ...apiParams.value })
      : (submit = val);
    submit = { ...initData.data.params, ...submit };
    if (props.api) {
      const res = await props.api(props.customApiParams || submit); // 使用父级给的api地址
      if (res.data && res.data.success) {
        //  最后判断如果有 max的话 截取max位置的内容
        if (props.max) {
          res.data.result = res.data.result.splice(0, props.max);
        } else {
          const records = [] as any;
          records.push(...(res.data.result.records || res.data.result));
          initData.data.recordsList = records;
          // 获取当前已选择的数据
          const map = new Map();
          const myData = [
            ...initData.data.selectedRowList,
            ...records,
            ...defaultRow.value,
          ];
          initData.data.selectedRowList = myData.filter((item) => {
            return !map.has(item.id) && map.set(item.id, item.id);
          });
        }
        // 请求到的数据全部给赋值
        initData.data.result = res.data.result;
        if (initData.data.result) {
          emit('parentComponentData', initData.data.result);
        }
      }
    } else if (props.dataList.length >= 0) {
      initData.data.result = reactive<any>([...props.dataList]);
    }
    initData.data.loading = false;
  }

  // 点击按钮进行回调方法
  function handleClickBtn(data: any) {
    const { callback } = data;
    emit(callback, data);
  }

  // 复制商品
  const copyGoods = (v: string) => {
    router.push({ name: 'goods-operation', query: { copyId: v } });
  };

  // 监听分页值的改变并进行查询
  watch(
    () => [initData.data.params, props.dataList, props.defaultSelectedKeys],
    (val) => {
      val ? init() : '';
    },
    {
      deep: true,
    }
  );
  // 初始化监听
  watch(
    () => [props.apiParams],
    (val: any) => {
      delete initData.data.params.pageNumber;
      initData.data.params.pageNumber = 1;
    },
    { deep: true }
  );

  onMounted(() => {
    init();
    defaultRow.value = props.defaultSelectedKeys.map((item: any) => {
      item.id = item.skuId;
      return item;
    });
    // initData.data.selectedList = props.defaultSelectedKeys;
    initData.data.selectedList = props.defaultSelectedKeys.map((item: any) => {
      return item.skuId;
    });
  });
  defineExpose({
    init,
  });
</script>

<style lang="less" scoped>
  .btn {
    margin-right: 10px;
  }

  .loader-animate {
    width: 100%;
    height: 100%;
    background: linear-gradient(
      -60deg,
      var(--color-fill-2) 25%,
      var(--color-neutral-3) 40%,
      var(--color-fill-3) 55%
    );
    background-size: 400% 100%;
    animation: loop-circle 1.5s cubic-bezier(0.34, 0.69, 0.1, 1) infinite;
  }

  @keyframes loop-circle {
    0% {
      background-position: 100% 50%;
    }

    100% {
      background-position: 0 50%;
    }
  }

  .qrcode {
    width: 15px;
  }

  .paginationBox {
    margin-top: 18px;
    display: flex;
    flex-direction: row-reverse;
  }
  .copy-goods {
    font-size: 12px;
    margin-left: 5px;
    margin-top: 2px;
    color: #999999;
    cursor: pointer;
  }
</style>
